package com.mikao.service.impl;

import com.mikao.dao.OrderDao;
import com.mikao.dto.bo.OrderForm;
import com.mikao.dto.bo.SendForm;
import com.mikao.dto.vo.DateDto;
import com.mikao.dto.vo.OrdersDto;
import com.mikao.dto.vo.RspDataTableDto;
import com.mikao.entity.Orders;
import com.mikao.mybatis.mapper.OrderFormMapper;
import com.mikao.service.OrderService;
import com.mikao.utils.DateCheckUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;

/**
 * @author kenny
 */

@Service
public class OrderServiceImpl implements OrderService {

    private final OrderFormMapper orderFormMapper;
    private OrderDao orderDao;

    public OrderServiceImpl(OrderFormMapper orderFormMapper, OrderDao orderDao) {
        this.orderFormMapper = orderFormMapper;
        this.orderDao = orderDao;
    }

    @Override
    public RspDataTableDto<OrdersDto> orderList(OrderForm orderForm) {
        OrderForm form = this.convertDate(orderForm);
        List<OrdersDto> orderList = orderFormMapper.orderList(form);
        return new RspDataTableDto<>(orderForm.getDraw(), orderDao.count(), orderList);
    }

    @Override
    public void sendGoods(SendForm sendForm) {
        Orders orders = orderDao.findOne(sendForm.getId());
        orders.setExpressCode(sendForm.getExpressCode());
        orders.setType(3);
        orderDao.saveAndFlush(orders);
    }

    private OrderForm convertDate(OrderForm waiterStatementForm) {
        DateDto formatDate;
        if (!StringUtils.isEmpty(waiterStatementForm.getDateRangePicker())) {
            try {
                formatDate = DateCheckUtil.getFormatDate(waiterStatementForm.getDateRangePicker());
                waiterStatementForm.setStartTime(formatDate.getStartTime());
                waiterStatementForm.setEndTime(formatDate.getEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
                return waiterStatementForm;
            }
        } else {
            waiterStatementForm.setEndTime(null);
            waiterStatementForm.setStartTime(null);
        }
        return waiterStatementForm;
    }
}
